﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;

namespace HYRevitCode.ElementFilterUtility
{
	public class ElementFilter
	{
		public static IList<Element> FindSpecialElements(Autodesk.Revit.DB.Document doc, Type targetType, BuiltInCategory catagory)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			filteredElementCollector.OfClass(targetType);
			if (filteredElementCollector != null)
			{
				filteredElementCollector.OfCategory(catagory);
			}
			return filteredElementCollector.ToElements();
		}

		public static IList<Element> FindSpecialInstance(Autodesk.Revit.DB.Document doc, ICollection<ElementId> idCol, BuiltInCategory catagory, string symbolName)
		{
			IList<Element> list = new List<Element>();
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc, idCol);
			filteredElementCollector.OfClass(typeof(FamilyInstance));
			if (filteredElementCollector != null)
			{
				filteredElementCollector.OfCategory(catagory);
			}
			foreach (Element element in filteredElementCollector.ToElements())
			{
				FamilyInstance familyInstance = (FamilyInstance)element;
				if (familyInstance.Symbol.Name == symbolName)
				{
					list.Add(familyInstance);
				}
			}
			return list;
		}

		public static IList<Element> FindTypesInFamily(Autodesk.Revit.DB.Document doc, Type targetType, string familyName, BuiltInCategory catagory)
		{
			IEnumerable<Element> enumerable = ElementFilter.FindSpecialElements(doc, targetType, catagory);
			List<Element> list = new List<Element>();
			foreach (Element element in enumerable)
			{
				if (element.get_Parameter(BuiltInParameter.ALL_MODEL_FAMILY_NAME).AsString().Equals(familyName))
				{
					list.Add(element);
				}
			}
			return list;
		}

		public static Element FindElementType(Autodesk.Revit.DB.Document doc, Type targetType, string familyName, string typeName, BuiltInCategory catagory)
		{
			IEnumerable<Element> enumerable = ElementFilter.FindSpecialElements(doc, targetType, catagory);
			Element result = null;
			foreach (Element element in enumerable)
			{
				if (element.Name.Equals(typeName) && element.get_Parameter(BuiltInParameter.ALL_MODEL_FAMILY_NAME).AsString().Equals(familyName))
				{
					result = element;
					break;
				}
			}
			return result;
		}

		public static Family FindFamily(Autodesk.Revit.DB.Document doc, string familyName)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			filteredElementCollector.OfClass(typeof(Family));
			if (filteredElementCollector != null)
			{
				foreach (Element element in filteredElementCollector.ToElements())
				{
					if (((Family)element).Name == familyName)
					{
						return (Family)element;
					}
				}
			}
			return null;
		}
	}
}
